package com.bbcare.followup.plat.controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.service.IXCXService;
import com.bbcare.followup.plat.entity.*;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;


/**
 * 处理小程序服务端发送的请求。（这些请求都是没有session的）
 */
@Controller
@RequestMapping("/xcx")
public class XCXController {
    private static Logger logger = Logger.getLogger(XCXController.class);

    @Autowired
    private IXCXService xcxService;

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IContentTemplDAO contentTemplDao;

    @Autowired
    private IPatientTaskContentDAO patientTaskConDao;


    @ResponseBody
    @RequestMapping(value = "/query_task_templ_by_type5", method = RequestMethod.POST)
    public Map<String, Object> queryTemplByTaskId(@RequestParam(value = "task_id", required = true) final String taskId)  {
        logger.info("++++queryTemplByTaskId() http request parameter task_id:"+taskId);
        if (null == taskId || taskId.isEmpty()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无taskId节点！"));
        }

        HashMap<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("taskId",    taskId);
        argMap.put("contTemplType", "5");
        HashMap<String, Object> dataOut = new HashMap<String, Object>();
        try {
            List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(argMap);
            if (null != ptcList && !ptcList.isEmpty())  {
                final String templVerId = ptcList.get(0).getTemplVersionid();
                int index = templVerId.indexOf("ver");
                if (index < 0)  {
                    new RuntimeException("未找到该任务对应的模板！！");
                }
                final String templId    = templVerId.substring(0, index) + templVerId.substring(index + "ver".length());
                HashMap<String, Object> contVerMap = new HashMap<String, Object>();
                contVerMap.put("templId",       templId);   //本值对应表fu_contenttemplversion_dict.templ_id。
                contVerMap.put("templVersion",  1);  //本值对应表fu_contenttemplversion_dict.templ_version。
                List<ContentTemplVersion> ctvList = contentTemplDao.selectContentDataByTempl(contVerMap);
                if (null != ctvList && !ctvList.isEmpty()) {
                    dataOut.put("success", "true");
                    dataOut.put("data",     ctvList);
                } else {
                    dataOut.put("success", "false");
                }
            }
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
            dataOut.put("success","false");
        }

        return dataOut;
    }

    @ResponseBody
    @RequestMapping(value = "/query_task_content", method = RequestMethod.POST)
    public ResultModel<HashMap<String, Object>> queryTaskContent(@RequestBody String arg)  {
        logger.info("++++queryTaskContent() http request parameters:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String taskId = jsonData.getString("taskId");
        if (null == taskId || taskId.isEmpty()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无taskId节点！"));
        }

        HashMap<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("taskId",    taskId);
        HashMap<String, Object> retMap = new HashMap<String, Object>();
        try {
            List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(argMap);
            retMap.put("success","true");
            retMap.put("PtTaskcontentInfo",  ptcList);
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
            retMap.put("success","false");
        }

        return new ResultModel(retMap);
    }

    @ResponseBody
    @RequestMapping(value = "/query_task_content_data", method = RequestMethod.POST)
    public ResultModel<HashMap<String, Object>> queryTaskContentData(@RequestBody String arg)  {
        logger.info("++++queryTaskContentData() http request parameters:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String taskId = jsonData.getString("taskId");
        if (null == taskId || taskId.isEmpty()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无taskId节点！"));
        }

        HashMap<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("taskId",    taskId);
        HashMap<String, Object> retMap = new HashMap<String, Object>();
        try {
            List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(argMap);
            retMap.put("success","true");
            retMap.put("PtContentdataInfo",  ptTaskConList);
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
            retMap.put("success","false");
        }

        return new ResultModel(retMap);
    }

    /**
     * 查询模板内容。
     * @param templId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/query_content_templ_data", method = RequestMethod.POST)
    public Map<String, Object> queryContentTmplData(@RequestParam(value = "templ_id", required = true) final String templId,
                                                    @RequestParam(value = "templ_ver", required = true) final Integer templVer) throws Exception {
        logger.info("++++queryContentTmplData() parameter templ_id:"+templId+", templ_ver:"+templVer);
        // 获取内容模板.
        HashMap<String, Object> contVerMap = new HashMap<String, Object>();
        contVerMap.put("templId",       templId);   //本值对应表fu_contenttemplversion_dict.templ_id。
        contVerMap.put("templVersion",  templVer);  //本值对应表fu_contenttemplversion_dict.templ_version。
        List<ContentTemplVersion> ctvList = contentTemplDao.selectContentDataByTempl(contVerMap);
        final int size  = ctvList.size();
        Map<String, Object> dataOut = new HashMap<>();
        String msg  = "根据参数templId["+templId+"]templVersion["+templVer+"]找到了【"+size+"】条数据。";
        dataOut.put("message", msg);
        if (null != ctvList && 0 != size) {
            dataOut.put("success", "true");
            dataOut.put("data",     ctvList);
        } else {
            dataOut.put("success", "false");
        }

        return dataOut;
    }

    /**
     * 新患者建档。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/add_new_patient")
    public ResultModel<Map<String, Object>> addNewPatient(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++addNewPatient() receive a http request, data is:"+arg);
        xcxService.checkRequest_addnewpatient(arg);
        long beginTime = System.currentTimeMillis();

        JSONObject jsonArg = JSON.parseObject(arg);
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        Map<String, Object> servParamMap = jsonData;

        //操作类型默认：2（门诊）。
        final String opType = "2";
        //操作编码默认：1000（患者建档）。
        final String opCode = "1000";
        //操作备注。
        final String opNote = "小程序建档";
        final String userType = "2";  //孕产妇（母亲），暂时写死，回头完善。

        //患者性别。
        final String genderParam = jsonData.getString("gender");
        String gender = genderParam.trim();
        // 转换性别
        if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        }
        //患者姓名。
        final String patientName = jsonData.getString("patientName");
        //创建新患者的时间。
        final String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        //患者生日。
        final String birthday = jsonData.getString("birthday");
        //患者胎龄（孕周）。
        final Integer pregnancyDay = Integer.valueOf(jsonData.getString("pregnancyDay"));
        //患者预产期。
        final String expectDay  = jsonData.getString("expectDay");
        //患者联系电话。
        final String phoneNo= jsonData.getString("phoneNo");
        final String queueId= jsonData.getString("queueId");
        final String deptId = jsonData.getString("deptId");
        final String tenantId = jsonData.getString("tenantId");
        final String author = "小程序建档";
        final String authorId = author;
        logger.info("++++addNewPatient() parameters from xcxadmin queueId:"+queueId+", patientName:"+patientName+", tenantId:"+tenantId+", deptId:"+deptId+", phoneNo:"+phoneNo+", expectDay:"+expectDay+", pregnancyDay:"+pregnancyDay+", birthday:"+birthday+", gender:"+gender);

        Patient pt = new Patient();
        pt.setUserName(patientName);
        pt.setFirstName(patientName.substring(0, 1));
        pt.setGender(gender);
        pt.setBirthday(birthday);
        pt.setPhoneNo(phoneNo);
        pt.setPregnancyDay(pregnancyDay);
        pt.setExpectedDay(expectDay);
        pt.setUserType(userType);
        pt.setSourceType(Constants.PATIENT_SOURCE_TYPE_MINI_PROGRAM);
        pt.setCreateTime(currTime);
        pt.setUpdateTime(currTime);
        pt.setCreateAuthor(author);


        final String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        servParamMap.put("patient", pt);
        servParamMap.put("queueId", queueId);
        servParamMap.put("opCode", opCode);
        servParamMap.put("opNote", opNote);
        servParamMap.put("opType", opType);
        servParamMap.put("userType", userType);
        servParamMap.put("authorName", author);
        servParamMap.put("authorId", authorId);
        servParamMap.put("tenantId", tenantId);
        servParamMap.put("deptId", deptId);
        servParamMap.put("updateTime", currTime);
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("contentData", jsonData.getJSONObject("questions"));
        /*
         * insert pt_user_info
         * insert pt_task_info
         * insert pt_queuescheme_info
         */
        Map<String, Object> patientMap = patientService.registerPatient(servParamMap);
        logger.info("++++create a new patient:"+JSON.toJSONString(patientMap));
        long duration = System.currentTimeMillis() - beginTime;
        logger.info("++++addNewPatient() take "+duration+" millis to create a new patient.");

        return new ResultModel<Map<String, Object>>(patientMap);
    }

    /**
     * 查询患者的小程序通知消息（下次检查提醒）。
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query_xcjctx_msg", method = RequestMethod.POST)
    public ResultModel<HashMap<String, Object>> queryXCJCTXmsg(@RequestBody String arg)  {
        logger.info("++++queryXCJCTXmsg() http request parameters:"+arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String tenantId   = jsonData.getString("tenant_id");
        final String patId      = jsonData.getString("patient_id");
        if (null == tenantId || tenantId.isEmpty()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无tenant_id节点！"));
        }
        if (null == patId || patId.isEmpty()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无patient_id节点！"));
        }

        HashMap<String, Object> retMap = new HashMap<String, Object>();
        try {
            //TODO.
            List<Map<String,Object>> resultList    = xcxService.queryXCJCTXmsg(tenantId, patId);
            retMap.put("success","true");
            retMap.put("rows",  resultList);
        } catch (Exception ex)  {
            logger.error(ex.getMessage());
            retMap.put("success","false");
        }

        return new ResultModel(retMap);
    }
}
